import { Service } from 'egg';
import { Setting } from '../model/Setting';
import * as path from 'path';
import * as fs from 'fs';

export default class SettingService extends Service {
    /**
     * 查找全部系统设置
     */
    public async searchAllSetting() {
        const setting = this.ctx.model.Setting.findAll<Setting>({ attributes: ['setting_key', 'setting_value'] });
        return setting;
    }

    /**
     * 更新系统设置
     */
    public async updateSetting(param: any) {
        try {
            for (let i = 0; i < param.length; i++) {
                await this.app.model.Setting.update({ setting_value: param[i]['setting_value'] }, { where: { setting_key: param[i]['setting_key'] } });
                if(param[i]['setting_key']=='homePageImg'){
                    try{
                        const oldImgName=param[i]['setting_value'];
                        const newImgName='wechat.png';
                        const oldImgUrl=path.join(__dirname,'../public/img',oldImgName);
                        const newImgUrl=path.join(__dirname,'../public/img',newImgName);
                        fs.copyFileSync(oldImgUrl,newImgUrl);
                    }catch(e){
                        throw new Error(JSON.stringify({ code: 2, msg: '复制图片失败' }));
                    }
                }
            }
        } catch (e) {
            console.log(e);
            throw new Error(JSON.stringify({ code: 2, msg: '更新失败' }));
        }
    }

}
